import { isCheckPermission } from '@/access';
import { getChatLog } from '@/services/ant-design-pro/api';
import { massEmail } from '@/services/ant-design-pro/communicate';
import { useIntl, useModel } from '@umijs/max';
import { App, Button, Card, Input, Popover, Space } from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import './index.css';

const Exchange: React.FC = () => {
  const { message } = App.useApp();
  const [currentUser, setCurrentUser] = useState('');
  const { initialState } = useModel('@@initialState');
  const ws = useRef<WebSocket | null>(null);
  const [log, setLog] = useState<any>([]);
  const [text, setText] = useState<string>('');
  const [loading, setLoading] = useState<boolean>(false);
  const [isComposing, setIsComposing] = useState(false);
  const intl = useIntl();

  const isShowMassEmailBtn = () => {
    return isCheckPermission(initialState, '群发邮件', '按钮');
  };

  const textChangeHandler = (event: { target: HTMLInputElement }) => {
    setText((event.target as HTMLInputElement).value);
  };

  const handleComposition = (event: React.CompositionEvent<HTMLInputElement>) => {
    if (event.type === 'compositionstart') {
      setIsComposing(true); // 输入法开始输入
    } else if (event.type === 'compositionend') {
      setIsComposing(false); // 输入法输入结束
    }
  };

  function getCurrentUser() {
    const str: string = sessionStorage.getItem('user') as string;
    const jsonStr = JSON.parse(str);
    const name = jsonStr.username as string;
    setCurrentUser(name);
  }
  const updateScrol = () => {
    const el = document.querySelector('.communicate');
    const tar: any = el?.children[0];
    const allH = tar?.scrollHeight as number;
    const H = tar?.clientHeight as number;
    tar.scrollTop = allH - H;
  };
  const initWs = () => {
    const str: string = sessionStorage.getItem('user') as string;
    const jsonStr = JSON.parse(str);
    const id = jsonStr.user as string;
    ws.current = new WebSocket(WS_URL, id) as WebSocket;
  };
  function updateLog(str: string) {
    const mode = {
      name: '',
      time: '',
      msg: '',
      timeUnix: 0,
    };
    const reg = new RegExp(/\s\d{13}\s/);
    const res = str.split(reg);
    mode.name = res[0];
    mode.msg = res[1];
    const t = str.match(reg);
    if (t) {
      // mode.time = t[0].trim();
      mode.timeUnix = Number(t[0].trim());
      mode.time = new Date(Number(t[0].trim())).toLocaleString();
    }
    setLog([...log, mode]);
  }
  useEffect(() => {
    ws.current?.addEventListener('message', (e) => {
      updateLog(e.data);
    });
    updateScrol();
  }, [log]);

  useEffect(() => {
    initWs();
    getCurrentUser();
    getChatLog().then((res: any) => {
      const arr: any = [];
      res.log.forEach((item: any) => {
        const mode = {
          name: '',
          time: '',
          msg: '',
          timeUnix: 0,
        };
        for (const key in item) {
          if (Object.prototype.hasOwnProperty.call(item, key)) {
            const ar = key.split('-');
            mode.name = ar[0];
            mode.timeUnix = Number(ar[1]);
            mode.time = new Date(Number(ar[1])).toLocaleString();
            mode.msg = item[key];
          }
        }
        arr.push(mode);
      });
      arr.sort((a: any, b: any) => {
        return a.timeUnix - b.timeUnix;
      });
      setLog(arr);
    });
    return () => {
      ws.current?.close();
    };
  }, []);

  function submit() {
    setText('');
    if (text.replace(/\s/g, '').length === 0) {
      return;
    }
    const res = currentUser + ' ' + Date.now() + ' ' + text;
    updateLog(res);
    ws.current?.send(res);
  }

  const handleKeyPress = (event: React.KeyboardEvent<HTMLInputElement>) => {
    if (event.key === 'Enter' && !isComposing) {
      submit();
    }
  };

  function chatLayout() {
    return log.map((item: any) => {
      if (item.name === currentUser) {
        return (
          <div key={item.time} className="right">
            {item.msg}
          </div>
        );
      } else {
        return (
          <p key={item.time} className="left">
            <span>
              {item.name}-{item.time}:{' '}
            </span>
            {item.msg}
          </p>
        );
      }
    });
  }
  async function handleEmail() {
    setLoading(true);
    const res = await massEmail();
    if (res.code === 0) {
      message.success(res.msg);
    } else {
      message.error(res.msg);
    }
    setLoading(false);
  }
  const content = (
    <div>
      <p>向用户管理中的所有用户的邮箱中发送一封邮件</p>
    </div>
  );
  return (
    <App>
      <div className="out">
        {isShowMassEmailBtn() && (
          <Popover
            content={content}
            title={intl.formatMessage({
              id: 'component.massEmail',
              defaultMessage: 'Mass Email',
            })}
          >
            <Button
              type="primary"
              loading={loading}
              onClick={handleEmail}
              style={{ marginBottom: '10px' }}
            >
              {intl.formatMessage({
                id: 'component.massEmail',
                defaultMessage: 'Mass Email',
              })}
            </Button>
          </Popover>
        )}
        <Card className="communicate" style={{ width: '100%' }}>
          {chatLayout()}
        </Card>
        <Space.Compact style={{ width: '100%', marginTop: '10px' }}>
          <Input
            placeholder={intl.formatMessage({
              id: 'component.chatRecords600Seconds',
              defaultMessage: 'Chat records saved for 600 seconds from sending',
            })}
            value={text}
            onChange={textChangeHandler}
            onCompositionStart={handleComposition}
            onCompositionEnd={handleComposition}
            onKeyDownCapture={handleKeyPress}
          />
          <Button onClick={submit} type="primary">
            {intl.formatMessage({
              id: 'component.send',
              defaultMessage: 'Send',
            })}
          </Button>
        </Space.Compact>
      </div>
    </App>
  );
};

export default Exchange;
